/**
 *购物车的操作 
 */

//同一调用
getCarts();

//1、ajac请求获取所有的购物车信息
function getCarts(){
	$.ajax({
		url: '/api/cart/getAll',
		type: 'get',
		data:{},
		dataType:'json',
		success:function(data){
			var html ="";
			
			$.each(data, function(index, item){
				html +='<div class="cart-goods clear">\
									<div class="col col-check">\
								<input type="checkbox" class="all" id="cart-'+item.id+'" value="'+item.id+'"/>\
								<label for="cart-'+item.id+'"></label> \
							</div>\
							<div class="col col-img">\
								<a href=""><img src="/upload/'+item.goods.pictures[0].name+'" /></a>\
							</div>\
							<div class="col col-name">\
								<a href="/goods?id='+item.goods.id+'">'+item.goods.name+' '+item.goods.version+' '+item.goods.color+'</a>\
							</div>\
							<div class="col col-price">\
								<span>'+item.goods.price+'</span>元\
							</div>\
							<div class="col col-count">\
								<div class="count-bar">\
									<a href="javascript:;" class="sub">-</a>\
									<span class="count">'+item.count+'</span>\
									<a href="javascript:;" class="add">+</a>\
								</div>\
							</div>\
							<div class="col col-total">\
								'+item.goods.price*item.count+'元\
							</div>\
							<div class="col col-action">\
								<a href="javascript:;"><i class="mi-icon icon-close"></i></a>\
							</div>\
						</div>';
			});
			$(".cart-list").html(html);
		},
		error:function(){
			
		}
	});
	
	//绑定+-操作  预绑定
	$(".cart-list").on("click", ".sub", function(){
		var count = $(this).parent().find(".count").text();
		count = parseInt(count) - 1;
		count = count < 1 ? 1:count;
		
		$(this).parent().find(".count").text(count);
		
		//重新计算小计
		//获取价格，
		var price = $(this).parents(".cart-goods").find(".col-price span").text();
		price = parseFloat(price);
		$(this).parents(".cart-goods").find(".col-total").text(price*count+'元');
		
		
		//更新服务器里的操作
		var id = $(this).parents(".cart-goods").find("input").val();
		updateCart(id, count);
	});
	
	$(".cart-list").on("click", ".add", function(){
		var count = $(this).parent().find(".count").text();
		count = parseInt(count) + 1;
		count = count < 1 ? 1:count;
		
		$(this).parent().find(".count").text(count);
		
		//重新计算小计
		//获取价格，
		var price = $(this).parents(".cart-goods").find(".col-price span").text();
		price = parseFloat(price);
		$(this).parents(".cart-goods").find(".col-total").text(price*count+'元');
		
		//更新服务器里的操作
		var id = $(this).parents(".cart-goods").find("input").val();
		updateCart(id, count);
	});
	
	//更新服务器里的操作
	function updateCart(id, count){
		$.ajax({
			url: '/api/cart/upload',
			type: 'get',
			data:{id: id, count: count},
			dataType: 'json',
			success:function(){
				
			},
			error:function(){
				
			}
		});
	}
	
}